package com.macro.mall.portal.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.macro.mall.portal.service.WxPayService;
import com.macro.mall.portal.wxpay.domain.WepayLog;
import com.macro.mall.portal.wxpay.helper.MyWeChatPayUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
@AllArgsConstructor
public class WxPayServiceImpl implements WxPayService {

    private final MyWeChatPayUtil myWeChantPayUtil;
//
//    private final StoreService storeService;
//
//    private final PartnerService partnerService;
//
//    private final WepayLogService wepayLogService;
//
//    private final OurPartnerService ourPartnerService;
//
//    private final CardService cardService;
//
//    private final RechargeServiceImpl rechargeService;
//
//    private final CarBeautyServiceImpl carBeautyService;

    @Override
    public Document callback(String req) {
        // 记录回调日志
        callBackLog(req);

        // 响应预设
        Document resXml = DocumentHelper.createDocument();
        Element resRoot = resXml.addElement("xml");
        resRoot.addElement("return_code").addCDATA("SUCCESS");
        resRoot.addElement("return_msg").addCDATA("OK");

        String orderNumber = null;

        try {
            Document reqXml = DocumentHelper.parseText(req);// 请求参数
            Element reqRoot = reqXml.getRootElement();

            String returnCode = reqRoot.element("return_code").getText();// 通信标识，接收正确参数
            if ("SUCCESS".equals(returnCode)) {
                // 校验签名
                boolean checkSign = myWeChantPayUtil.checkSign(reqXml);
                if (checkSign) {
                    // 业务结果，"SUCCESS"支付成功，"FAIL"支付失败
                    String resultCode = reqRoot.element("result_code").getText();
                    // 回调额外数据
                    String attachStr = reqRoot.element("attach").getText();
                    // 商户订单号
                    orderNumber = reqRoot.element("out_trade_no").getText();
                    // 订单金额，单位：分
                    String totalFee = reqRoot.element("total_fee").getText();
                    // 订单金额，单位：元
                    BigDecimal price = new BigDecimal(totalFee).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                    // 支付完成时间，格式为：yyyyMMddHHmmss
                    String payTime = reqRoot.element("time_end").getText();

                    JSONObject attachJson = new JSONObject(attachStr);
//                    ProudPayEnum proudPay = ProudPayEnum.toType(attachJson.optString("productPayType"));

                    try {
//                        switch (proudPay) {
//                            case CARD_CALLBACK:
//                                if ("SUCCESS".equals(resultCode)) {
//                                    log.info("进入卡支付微信回调：{}，orderNumber：{}", "成功", orderNumber);
//                                    // 卡支付
//                                    PayCardVo payCardVo = JSONArray.parseObject(attachStr, PayCardVo.class);
//                                    PayCallBankVo payCallBank = PayCallBankVo.builder()
//                                            .tradeStatus(resultCode)
//                                            .outTradeNo(orderNumber)
//                                            .totalAmount(price.toString())
//                                            .uid(payCardVo.getUid())
//                                            .shareCode(payCardVo.getShareCode())
//                                            .payType(PayTypeEnums.WE_PAY.value())
//                                            .cardType(payCardVo.getCardType())
//                                            .build();
//                                    String code = cardService.callbackProcessing(payCallBank);
//                                    if (!code.equals("SUCCESS")) {
//                                        throw new BadRequestException("卡支付微信回调异常!");
//                                    }
//                                } else {
//                                    log.info("进入卡支付微信回调：{}，orderNumber：{}", "失败", orderNumber);
//                                }
//                                break;
//                            default:
//                        }

                    } catch (Exception e) {
                        resRoot.remove(resRoot.element("return_code"));
                        resRoot.remove(resRoot.element("return_msg"));

                        resRoot.addElement("return_code").addCDATA("FAIL");
                        resRoot.addElement("return_msg").addCDATA(e.getMessage());
                    }

                } else {
                    resRoot.remove(resRoot.element("return_code"));
                    resRoot.remove(resRoot.element("return_msg"));

                    resRoot.addElement("return_code").addCDATA("FAIL");
                    resRoot.addElement("return_msg").addCDATA("签名失败");
                }

            } else {
                resRoot.remove(resRoot.element("return_code"));
                resRoot.remove(resRoot.element("return_msg"));

                resRoot.addElement("return_code").addCDATA("FAIL");
                resRoot.addElement("return_msg").addCDATA("通信标识：return_code=FAIL");
            }

        } catch (DocumentException e) {
            resRoot.remove(resRoot.element("return_code"));
            resRoot.remove(resRoot.element("return_msg"));

            resRoot.addElement("return_code").addCDATA("FAIL");
            resRoot.addElement("return_msg").addCDATA("参数格式校验错误：" + e.getMessage());
        }

        log.info("微信支付回调响应：{}，订单号：{}", resXml.getRootElement().asXML(), orderNumber);
        return resXml;
    }

    @Override
    public Document refundCallBack(String req) {
        Document resXml = DocumentHelper.createDocument();
        Element resRoot = resXml.addElement("xml");
        resRoot.addElement("return_code").addCDATA("SUCCESS");
        resRoot.addElement("return_msg").addCDATA("OK");

        try {
            Document reqXml = DocumentHelper.parseText(req);// 请求参数
            Element reqRoot = reqXml.getRootElement();

            String returnCode = reqRoot.element("return_code").getText();// 通信标识，接收正确参数
            if ("SUCCESS".equals(returnCode)) {
                String returnMsg = reqRoot.element("return_msg").getText();// 加密信息

//                String msg = AESUtil.decryptData(returnMsg, mchKey);


            } else {
                resRoot.element("return_code").addCDATA("FAIL");
                resRoot.element("return_msg").addCDATA("通信标识：return_code=FAIL");
            }

        } catch (DocumentException e) {
            resRoot.element("return_code").addCDATA("FAIL");
            resRoot.element("return_msg").addCDATA("参数格式校验错误" + e.getMessage());
        }

        return resXml;
    }

    /**
     * 回调函数日志记录
     *
     * @param source
     */
    private void callBackLog(String source) {
        WepayLog wepayLog = WepayLog.builder()
                .source(source)
                .build();

        try {
            Document reqXml = DocumentHelper.parseText(source);
            Element reqRoot = reqXml.getRootElement();

            Element returnCode = reqRoot.element("return_code");
            wepayLog.setReturnCode(returnCode != null ? returnCode.getText() : null);

            Element returnMsg = reqRoot.element("return_msg");
            wepayLog.setReturnMsg(returnMsg != null ? returnMsg.getText() : null);

            wepayLog.setCheckSign(myWeChantPayUtil.checkSign(reqXml) ? "true" : "false");

            Element resultCode = reqRoot.element("result_code");
            wepayLog.setResultCode(resultCode != null ? resultCode.getText() : null);

            Element errCode = reqRoot.element("err_code");
            wepayLog.setErrCode(errCode != null ? errCode.getText() : null);

            Element errCodeDes = reqRoot.element("err_code_des");
            wepayLog.setErrCodeDes(errCodeDes != null ? errCodeDes.getText() : null);

            Element totalFee = reqRoot.element("total_fee");
            wepayLog.setTotalFee(totalFee != null ? totalFee.getText() : null);

            Element transactionId = reqRoot.element("transaction_id");
            wepayLog.setTransactionId(transactionId != null ? transactionId.getText() : null);

            Element outTradeNo = reqRoot.element("out_trade_no");
            wepayLog.setOutTradeNo(outTradeNo != null ? outTradeNo.getText() : null);

            Element attach = reqRoot.element("attach");
            wepayLog.setAttach(attach != null ? attach.getText() : null);

            Element timeEnd = reqRoot.element("time_end");
            wepayLog.setTimeEnd(timeEnd != null ? timeEnd.getText() : null);

        } catch (DocumentException e) {
        }
        log.info("微信支付日志记录");
//        wepayLogService.save(wepayLog);
    }
}

